package com.example.demo.controller;

import com.example.demo.entity.Order;
import com.example.demo.entity.OrderProps;
import com.example.demo.entity.User;
import com.example.demo.service.OrderRepository;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;


import javax.validation.Valid;

@Controller
@RequestMapping("/orders")
@SessionAttributes("order")
//@ConfigurationProperties(prefix = "taco.orders") //读取配置文件。只能用到控制器和特定的bean中,
// 实际上会放到一种特定类型的bean中，这种bean就是配置数据
public class OrderController {

    private OrderProps orderProps;

    private OrderRepository orderRepo;

    public OrderController(OrderRepository orderRepo, OrderProps orderProps) {
        this.orderRepo = orderRepo;
        this.orderProps = orderProps;
    }

    @GetMapping("/current")
    public String orderForm() {
        return "orderForm";
    }

    @PostMapping
    // 也可以在参数中添加Principal 通过 User user= userRepository.findByUsername(principal.getName())
    public String processOrder(@Valid Order order, Errors errors, SessionStatus sessionStatus, Authentication authentication) {
        if (errors.hasErrors()) {
            return "orderForm";
        }
        //principal.getName() 会返回当前认证对象的名称
        User user = (User) authentication.getPrincipal();  //返回一个UserDetails的实例
        order.setUser(user);
        orderRepo.save(order);
        sessionStatus.setComplete();

        return "redirect:/";
    }


    @GetMapping
    public String ordersForUser(@AuthenticationPrincipal User user, Model model) {
        Pageable pageable = PageRequest.of(0, orderProps.getPageSize()); //pageable是根据页号和每页数量选取子集的一种方法
        model.addAttribute("orders", orderRepo.findByUserOrderByPlacedAtDesc(user, pageable));
        return "orderList";
    }

}
